(function () {
    let _index = 1
    const getIndex = function () {
        return _index++
    }

    function NativeDialog(options) {
        var me = this
        me.showCancel = true
        Object.keys(options || {}).forEach(function (name) {
            me[name] = options[name] ?? ''
        })
        me.index = getIndex()
        me.id = `native-dialog-${me.index}`
    }

    NativeDialog.prototype.mount = function () {
        var me = this
        const view = me.view()
        const dv = document.createElement('div')
        dv.innerHTML = view
        document.body.appendChild(dv)
        me.el = document.getElementById(me.id)
        me.bind()
    }

    NativeDialog.prototype.view = function () {
        var me = this
        const cancelBtn = () => {
            if (!me.showCancel) {
                return ''
            }
            return `<button class="native-dialog-ft-cancel" id="cancel">${me.cancelText || '取消'}</button>`
        }
        const html = `<dialog class="native-dialog" id="${me.id}" data-index="${me.index}" style="${me.style}">
            <h3 class="native-dialog-hd">${me.title || '提示'}</h3>
            <div class="native-dialog-bd">
                ${me.content || ''}
            </div>
            <div class="native-dialog-ft">
                <div>${me.footer || ''}</div>
                <div>
                    ${cancelBtn()}
                    <button class="native-dialog-ft-ok">${me.okText || '确定'}</button>
                </div>
            </div>
        </dialog>`

        return html
    }

    NativeDialog.prototype.show = function () {
        var me = this
        me.mount()
        me.el.showModal();
    }

    NativeDialog.prototype.hide = function () {
        var me = this
        me.el.close()
        me.el.parentNode.remove()
    }

    NativeDialog.prototype.bind = function () {
        var me = this
        const cancel = document.querySelector(`#${me.id} .native-dialog-ft-cancel`)
        const ok = document.querySelector(`#${me.id} .native-dialog-ft-ok`)

        cancel.addEventListener('click', function () {
            if (me.cancel) {
                me.cancel()
            } else {
                me.hide()
            }
        })

        ok.addEventListener('click', function () {
            if (me.ok) {
                me.ok()
            } else {
                me.hide()
            }
        })
    }

    window.create_native_dialog = function (options) {
        return new NativeDialog(options)
    }
})()